<?php
	require_once("user_session.php");
	$title = $_POST['title'];
	$fatherId = $_POST['fatherId'];
	
	# Re-Build the paragraph data 
	
	$paragraphStructure = array();
	$prIdArray = array();
	$pIdArray = array();
	$aParagraph = array();
	$ider = 0;
	
	$postArrayKeys = array_keys($_POST);
	
	#print_r($_POST);
	#echo "<br />======================================<br />";
	#print_r($postArrayKeys);
	#echo "<br />======================================<br />";
	
	$i = 0;//paragraph counter
	$j = 0;//one paragraph item counter
	for($k = 1;$k<count($postArrayKeys);$k ++){
		$tempJ = $j;
		#echo $postArrayKeys[$k] . " p_".$i ."<br />";
		if(ereg("p_".$i, $postArrayKeys[$k])){
			#echo "====>" . $i . " " . $j ."<br />";
			if(ereg("internal", $postArrayKeys[$k])){
				$aParagraph[2] = $_POST[$postArrayKeys[$k]];
			} else if (ereg("ref", $postArrayKeys[$k])){
				$aParagraph[1] = $_POST[$postArrayKeys[$k]];
			} else {
				$aParagraph[0] = $_POST[$postArrayKeys[$k]];
			}
			$j ++;
		} else if($j==0 && $i<count($postArrayKeys)){
			$i++;
			$k--;
		} else if($j!=0 && $tempJ == $j){
			$paragraphStructure[] = $aParagraph;
			
			if(count($aParagraph[2])!=0){
				foreach($aParagraph[2] as $internalLinkId){
					if(EKDocument::testExist($internalLinkId) == false){
						$ider ++;
						echo "<script language=javascript>\n".
					        "alert(\"Internal Link: ". $internalLinkId ." is not legal\");\n".
					        "</script>";
					}
				}
			}
			
			unset($aParagraph);
			$i ++;
			$k = $k - 1;
			$j = 0;
		}
		
	}
	
	#print_r($paragraphStructure);
	#echo "<br />======================================<br />";
	#print_r($prIdArray);
	#echo "<br />======================================<br />";
	#print_r($pIdArray);
		
	if($ider == 0){
	 
		# Save Doc
		if($fatherId == "null"){
			if(!EKDocument::testExist("_0")){
				$id = EKDocument::createNewDocNode($title,$fatherId, $paragraphStructure);
				echo "<script language=javascript>\n".
					        "alert(\"". "New ROOT has been set! " ."\");\n".
					        "self.location=\"document.php?id=".$id."&method=v\";\n".
					        "</script>";
			} else {
				echo "ROOT has been set already!";
			}
		} else {
			$id = EKDocument::createNewDocNode($title,$fatherId, $paragraphStructure);
			echo "<script language=javascript>\n".
					        "alert(\"". "New Document Added Successfully! " ."\");\n".
					        "self.location=\"document.php?id=".$id."&method=v\";\n".
					        "</script>";
		}
		
	} else {
		echo "<script language=javascript>window.history.back();</script>";
	}

?>